/**
 * 
 */
package cn.mxz.robots.province;

import java.io.File;
import java.io.FileInputStream;
import java.util.Scanner;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

import org.apache.poi.hwpf.extractor.WordExtractor;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.select.Elements;

import cn.mxz.crawler_single.basic.Request;
import cn.mxz.rds.pojo.GaoKaoProvince;
import cn.mxz.rds.pojo.GaoKaoRank;
import cn.mxz.rds.service.GaoKaoProvinceService;
import cn.mxz.rds.service.GaoKaoRankService;
import cn.mxz.robots.basic.local.Exam;
import cn.mxz.robots.basic.local.IRank;
import cn.mxz.robots.pojo.Student;

/**
 * 北京
 * 排名：true
 * 去年排名:完成
 * 
 * @author cuizhennan<cuizhennan@mouge.wang>
 * @author chenmin<chenmin@mouge.wang>
 * @since 2015-06-22
 */
public class Beijing extends Exam implements IRank
{
	public static void main(String[] args)
	{
		Student student = new Student("080951114", "15110108152849", "mxzqwe", "234", "l");
		Beijing gansu = new Beijing(student);
		System.out.println(gansu.getCaptcha());
		System.out.println("请输入验证码：");
		@SuppressWarnings("resource")
		String captcha = new Scanner(System.in).next();
		System.out.println(gansu.login(captcha));

	}

	public Beijing(Student student)
	{
		super(student);
	}

	@Override
	public String login(String captcha)
	{
		Request loginRequest = new Request("http://query.bjeea.cn/queryService/rest/score/103", mSha1);
		Document paraDocument = Jsoup.parse(curlPost(loginRequest));
		loginRequest.setCharSet("utf-8");
		loginRequest.addHeader("Referer", "http://query.bjeea.cn/queryService/rest/score/103");
		loginRequest.addParams("modeId", "103");
		loginRequest.addParams("examId", paraDocument.select("input[name=examId]").val());
		loginRequest.addParams("examNo", mStudent.getStudentId());
		loginRequest.addParams("examinneNo", mStudent.getStudentPwd());
		loginRequest.addParams("gaoKaoList", captcha);
		String loginHtml = curlPost(loginRequest);
		JSONObject resultObject = new JSONObject();

		if (loginHtml.contains("gaoKaoList"))
		{
			resultObject.put("result", LOGIN_SUCCESS);
			resultObject.put("data", loginParseHtml(loginHtml));
		}
		else if (loginHtml.contains("准考证号"))
		{
			resultObject.put("result", ERROR);
			resultObject.put("data", NOT_EXIST_USER);
		}
		else if (loginHtml.contains("验证码错误"))
		{
			resultObject.put("result", ERROR);
			resultObject.put("data", WRONG_CAPTCHA);
		}
		else
		{
			resultObject.put("result", ERROR);
			resultObject.put("data", INTERNAL_SERVER_ERROR);
		}

		return resultObject.toString();
	}

	@Override
	public String loginParseHtml(String parseHtml)
	{
		JSONObject login = JSONObject.fromObject(parseHtml);
		JSONArray gaokaoList = JSONArray.fromObject(login.get("gaoKaoList"));
		JSONObject data = new JSONObject();

		data.put("exam_id", mStudent.getStudentPwd());
		data.put("name", login.get("name"));
		JSONObject subjectJsonObject = JSONObject.fromObject(gaokaoList.get(4));
		data.put("ranking", getRank(33, subjectJsonObject.get("kmcj").toString(), mStudent.getType()));
		data.put("province", "北京市");
		JSONObject scoreObject = new JSONObject();

		subjectJsonObject = JSONObject.fromObject(gaokaoList.get(0));
		scoreObject.put("语文", subjectJsonObject.get("kmcj"));
		scoreObject.put("语文选择题得分", subjectJsonObject.get("xztfs"));
		subjectJsonObject = JSONObject.fromObject(gaokaoList.get(1));
		scoreObject.put("数学", subjectJsonObject.get("kmcj"));
		scoreObject.put("数学选择题得分", subjectJsonObject.get("xztfs"));
		subjectJsonObject = JSONObject.fromObject(gaokaoList.get(2));
		scoreObject.put("外语", subjectJsonObject.get("kmcj"));
		scoreObject.put("外语选择题得分", subjectJsonObject.get("xztfs"));
		subjectJsonObject = JSONObject.fromObject(gaokaoList.get(3));
		scoreObject.put("综合", subjectJsonObject.get("kmcj"));
		scoreObject.put("综合选择题得分", subjectJsonObject.get("xztfs"));
		subjectJsonObject = JSONObject.fromObject(gaokaoList.get(4));
		scoreObject.put("总分", subjectJsonObject.get("kmcj"));

		data.put("score", scoreObject.toString());

		return data.toString();
	}

	@Override
	public void initRank()
	{

		GaoKaoProvinceService provinceService = new GaoKaoProvinceService();
		GaoKaoProvince province = provinceService.get(2 + 31);
		GaoKaoRankService rankService = new GaoKaoRankService();

		String rankHtml = curlGet(new Request("http://www.bjeea.cn/html/bjeeagg/2015/0623/58108.html"));
		Document rankDom = Jsoup.parse(rankHtml);
		Elements as = rankDom.select("table").get(0).select("tr");
		Integer pre = 0;
		int asSize = as.size();
		for (int i = 3; i < asSize; i++)
		{
			// 理科排名
			// String scoreString = as.get(i).select("td").get(0).text();
			// String countString = as.get(i).select("td").get(3).text();
			// String leiji = as.get(i).select("td").get(4).text();
			String scoreString = as.get(i).select("td").get(0).text();
			String countString = as.get(i).select("td").get(7).text();
			String leiji = as.get(i).select("td").get(8).text();

			// 文科排名
			// String scoreString = as.get(i).select("td").get(0).text();
			// String countString = as.get(i).select("td").get(1).text();
			// String leiji = as.get(i).select("td").get(2).text();

			// String scoreString = as.get(i).select("td").get(0).text();
			// String countString = as.get(i).select("td").get(5).text();
			// String leiji = as.get(i).select("td").get(6).text();

			// 此分数段没有人就跳过
			if (countString.equals("　"))
				continue;

			Integer count = Integer.parseInt(countString);
			Integer ranking = pre + 1;
			pre = Integer.parseInt(leiji);

			Integer score = null;
			if (scoreString.contains("-"))
			{
				String beginString = regexMatch(scoreString, "(\\d+)-");
				String endString = regexMatch(scoreString, "-(\\d+)");
				Integer bs = Integer.parseInt(beginString);
				Integer es = Integer.parseInt(endString);
				Integer inc = count / 10;
				for (int j = es; j > bs - 1; j--)
				{
					score = j;
					if (j != es)
					{
						ranking += inc;
					}
					count = inc;
					GaoKaoRank rank = new GaoKaoRank();

					rank.setScore(score);
					rank.setCount(count);
					rank.setType(BEN_KE_LI_KE);
					rank.setGaoKaoProvince(province);
					rank.setRanking(ranking);

					// rankService.save(rank);

					System.out.println(rank);
					System.out.println("score: " + scoreString + "count: " + countString + "rank: " + ranking);
				}
			}
			else
			{
				score = Integer.parseInt(scoreString);
				GaoKaoRank rank = new GaoKaoRank();

				rank.setScore(score);
				rank.setCount(count);
				rank.setType(BEN_KE_LI_KE);
				rank.setGaoKaoProvince(province);
				rank.setRanking(ranking);

				rankService.save(rank);
				System.out.println("score: " + scoreString + "count: " + countString + "rank: " + ranking);
				System.out.println(rank);
			}
		}
		System.out.println("total records: " + asSize);
	}

	@Override
	public void lastYearRank()
	{
		File file = new File("/home/chenmin/Desktop/wen.doc");

		try
		{
			FileInputStream fis = new FileInputStream(file);
			WordExtractor wordExtractor = new WordExtractor(fis);
			String[] paragraph = wordExtractor.getParagraphText();
			for (int i = 12; i < paragraph.length; i += 6)
			{
				String score = regexMatch(paragraph[i], "(.*)");
				String counter = regexMatch(paragraph[i + 3], "(.*)");
				String ranking = regexMatch(paragraph[i + 4], "(.*)");

				Integer scores = valiteInteger(score);

				if (scores == 0)
					continue;

				Integer counters = valiteInteger(counter);
				Integer num = counters / 10;
				Integer rankings = valiteInteger(ranking);

				System.out.println(scores + ":" + counters + ":" + rankings);

				GaoKaoProvinceService provinceService = new GaoKaoProvinceService();
				GaoKaoProvince province = provinceService.get(2);
				GaoKaoRankService rankService = new GaoKaoRankService();
				GaoKaoRank rank = new GaoKaoRank();
				rank.setScore(scores);
				rank.setCount(counters);
				rank.setType(LI_KE);
				rank.setRanking(rankings);
				rank.setGaoKaoProvince(province);
				rankService.save(rank);

				for (int j = 1; j < 10; j++)
				{
					Integer scores1 = scores - j;
					Integer counters1 = counters;
					Integer rankings1 = num + rankings;
					System.out.println(scores1 + ":" + counters1 + ":" + rankings1);

					rank.setScore(scores1);
					rank.setCount(counters1);
					rank.setType(LI_KE);
					rank.setRanking(rankings1);
					rank.setGaoKaoProvince(province);
					rankService.save(rank);
				}

			}
		}
		catch (Exception e)
		{

		}
	}

	public Integer valiteInteger(String content)
	{
		return content.length() <= 1 && !content.contains("1") && !content.contains("2") && !content.contains("3") ? 0
				: Integer.parseInt(content);

	}

}
